import cv2
import os
from matplotlib import pyplot as plt
# from huafen import var
import numpy as np
ksize = (5,5)
sigmaX = 1
lower = 0
upper = 70
def detectEdges(img, ksize, sigmaX, lower, upper):
    res = cv2.Canny(cv2.GaussianBlur(img, ksize=ksize, sigmaX=sigmaX),lower,upper)
    return res
def select(img, kernel, threshold):
    points = []
    ksize = kernel.shape[0]
    for x in range(img.shape[0]-ksize+1):
        for y in range(img.shape[1]-ksize+1):
            local = img[x:x+ksize, y:y+ksize]
            if np.sum(local*kernel)<threshold:
                points.append((x+(ksize-1)//2, y+(ksize-1)//2))
    return points
def noNeighbor(l, p):
    x, y = p
    for i in range(x-3, x+1):
        for j in range(y-3, y+4):
            if (i,j) in l:
                return False
    return True
read_path = r'C:\Users\Admin\Desktop\imagedata\retif'
save_path = r'C:\Users\Admin\Desktop\imagedata\retif_points'
kernel = np.array([[-9,-9,-9,-9,-9],
                   [-9,16,16,16,-9],
                   [-9,16,16,16,-9],
                   [-9,16,16,16,-9],
                   [-9,-9,-9,-9,-9]])
threshold = -1000
point = []
for path in os.listdir(read_path):
    if 'png' in path:
        img_original = cv2.imread(read_path+'\\'+path,-1)
        img = cv2.cvtColor(img_original, code=cv2.COLOR_BGR2GRAY)
        cv2.imshow('gray',img)
        cv2.waitKey(0)
        points = select(img, kernel, threshold)
        edges = detectEdges(img, ksize, sigmaX, lower, upper)
        for x, y in points:
            if not np.sum(edges[x - 3:x + 4, y - 3:y + 4]):
                if noNeighbor(point, (x,y)):
                    point.append((x,y))
        for x,y in point:
            img_original[x-1:x+2, y-1:y+2] = [0,0,0]
        cv2.imshow('points', img_original)
        cv2.waitKey(0)
        cv2.imwrite(save_path+'\\'+path,img_original)
